//
//  XS_KCVideo.swift
//  XueDao
//
//  Created by 韩云智 on 2020/12/28.
//

import UIKit
import RxSwift
import RxCocoa
import AliyunPlayer

class XS_KCVideo: UIView {
    deinit {
        xsDebug { print("deinit: \(type(of: self))") }
        player?.stop()
        player?.destroy()
        player?.delegate = nil
    }
    
    private lazy var disposeBag = DisposeBag()
    lazy var actionPS = PublishSubject<XS_KCBaseVC.ActionType>()
    lazy var collectionPS = PublishSubject<Bool>()
    lazy var imgPS = PublishSubject<String>()
    lazy var modelPS = PublishSubject<XS_KCplayVideostsM>()
    lazy var livePS = PublishSubject<String>()
    
    lazy var player = AliPlayer()
    lazy var playerView = UIView()
    lazy var topView = UIView()
    lazy var botView = UIView()
    
    private lazy var isFullScreen = false
    private var windowFrame: CGRect!
    private var oldFrame: CGRect!
    private lazy var fullVC = XS_VPFullVC()
    
    private lazy var startBtn = XS_NoHighlightBtn()
    private lazy var playBtn = XS_NoHighlightBtn()
    private lazy var fullBtn = XS_NoHighlightBtn()
    private lazy var timeLab = UILabel.xsLabel(size: .scale*10, fontName: .regular, color: #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0))
    private lazy var slider = UISlider()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        upView()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func upView() {
        backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        playerView.frame = CGRect(x: 0, y: 0, width: 375, height: 240) * .scale
        addSubview(playerView)
        
        let imgV = UIImageView()
        playerView.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        imgPS.subscribe(onNext: { imgUrl in
            imgV.sd_setImage(with: URL(string: imgUrl))
        }).disposed(by: disposeBag)
        let pView = UIView()
        imgV.addSubview(pView)
        pView.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        
        topView.alpha = 0
        playerView.addSubview(topView)
        topView.snp.makeConstraints({
            $0.left.right.top.equalToSuperview()
            $0.height.equalTo(44)
        })
        
        let back = QMUIButton()
        back.setBackgroundImage(UIImage(named: "icon_返回备份"), for: .normal)
        topView.addSubview(back)
        back.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalToSuperview()
            $0.left.equalTo(16 + .safeSpace)
        })
        back.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.backFull()
            }).disposed(by: disposeBag)
        
        let share = QMUIButton()
        share.setBackgroundImage(UIImage(named: "icon_分享备份"), for: .normal)
        topView.addSubview(share)
        share.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalToSuperview()
            $0.right.equalTo(-16 - .safeSpace)
        })
        share.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let `self` = self else { return }
                self.player?.pause()
                if self.isFullScreen {
                    self.backFull()
                }
                self.actionPS.onNext(.分享)
            }).disposed(by: disposeBag)
        
        
        let xiangxue = QMUIButton()
        xiangxue.setBackgroundImage(UIImage(named: "icon_24px_收藏_1"), for: .normal)
        xiangxue.setBackgroundImage(UIImage(named: "icon_64_收藏_绿_1"), for: .selected)
        topView.addSubview(xiangxue)
        xiangxue.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalToSuperview()
            $0.right.equalTo(-56 - .safeSpace)
        })
        xiangxue.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.actionPS.onNext(.想学)
            }).disposed(by: disposeBag)
        collectionPS.subscribe(onNext: { set in
            xiangxue.isSelected = set
        }).disposed(by: disposeBag)
        
        
        botView.isHidden = true
        playerView.addSubview(botView)
        botView.snp.makeConstraints({
            $0.left.bottom.right.equalToSuperview()
            $0.height.equalTo(.scale*40)
        })
        
        playBtn.setBackgroundImage(UIImage(named: "编组播放"), for: .normal)
        playBtn.setBackgroundImage(UIImage(named: "icon_16px_暂停_1"), for: .selected)
        botView.addSubview(playBtn)
        playBtn.snp.makeConstraints({
            $0.width.height.equalTo(.scale*16)
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*16)
        })
        
        fullBtn.setBackgroundImage(UIImage(named: "icon_16px_暂停备份"), for: .normal)
        fullBtn.setBackgroundImage(UIImage(named: "icon_16px_暂停备份_1"), for: .selected)
        botView.addSubview(fullBtn)
        fullBtn.snp.makeConstraints({
            $0.width.height.equalTo(.scale*16)
            $0.centerY.equalToSuperview()
            $0.right.equalTo(-.scale*16)
        })
        fullBtn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let `self` = self else { return }
                if self.isFullScreen {
                    self.backFull()
                } else {
                    self.toFull()
                }
            }).disposed(by: disposeBag)
        
        slider.maximumValue = 1
        slider.maximumTrackTintColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.39)
        slider.minimumTrackTintColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        slider.setThumbImage(getImg(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)), for: .normal)
        botView.addSubview(slider)
        slider.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(.scale*48)
            $0.right.equalTo(-.scale*112)
        })
        
        botView.addSubview(timeLab)
        timeLab.snp.makeConstraints({
            $0.centerY.equalToSuperview()
            $0.left.equalTo(slider.snp.right).offset(.scale*8)
        })
        
        
        guard let player = player else { return }
//        player.isAutoPlay = true
        player.isLoop = false
        player.scalingMode = .init(0)
        player.playerView = pView
        player.delegate = self
        
        playBtn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                guard let select = self?.playBtn.isSelected else { return }
                if select {
                    player.pause()
                    self?.startBtn.isHidden = false
                    self?.startBtn.alpha = 1
                } else if player.duration > player.currentPosition {
                    player.start()
                    self?.startBtn.isHidden = true
                    self?.startBtn.alpha = 0
                } else {
                    player.prepare()
                    player.start()
                }
            }).disposed(by: disposeBag)
        slider.rx.controlEvent(.touchDown).asDriver()
            .drive(onNext: { _ in
                player.pause()
            }).disposed(by: disposeBag)
        slider.rx.controlEvent([.touchUpInside, .touchUpOutside, .touchDownRepeat, .touchCancel]).asDriver()
            .drive(onNext: { [weak self, weak player] _ in
                guard let `self` = self, let player = player else { return }
                let position = Int64(Float(player.duration) * self.slider.value)
                player.seek(toTime: position, seekMode: .init(0))
                if XS_Singleton.shared.canVideo {
                    player.start()
                }
            }).disposed(by: disposeBag)
        slider.rx.controlEvent(.valueChanged).asDriver()
            .drive(onNext: { [weak self] _ in
                guard let `self` = self else { return }
                let position = Int64(Float(player.duration) * self.slider.value)
                self.onCurrentPositionUpdate(player, position: position)
            }).disposed(by: disposeBag)
        
        startBtn.isHidden = true
        startBtn.setBackgroundImage(UIImage(named: "编组 2"), for: .normal)
        playerView.addSubview(startBtn)
        startBtn.snp.makeConstraints({
            $0.width.height.equalTo(.scale*48)
            $0.centerX.equalToSuperview()
            $0.centerY.equalToSuperview().offset(.scale*24)
        })
        startBtn.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                if XS_Singleton.shared.canVideo {
                    self?.startBtn.isHidden = true
                    self?.startBtn.alpha = 0
                    self?.botView.isHidden = false
                    player.start()
                } else {
                    xsWindow()?.xsShowMsg("当前使用移动网络，不可播放")
                }
            }).disposed(by: disposeBag)
        XS_Singleton.shared.canVideoPS
            .startWith(XS_Singleton.shared.canVideo)
            .subscribe(onNext: { [weak self] set in
                guard let `self` = self else { return }
                if !set, self.startBtn.isHidden {
                    player.pause()
                    self.startBtn.isHidden = false
                    self.startBtn.alpha = 1
                    self.botView.isHidden = true
                    xsWindow()?.xsShowMsg("当前使用移动网络，不可播放")
                }
                self.playBtn.isUserInteractionEnabled = set
            }).disposed(by: disposeBag)
        
        modelPS.subscribe(onNext: { [weak self] item in
            guard let `self` = self else { return }
            self.slider.value = 0
            NotificationCenter.default.post(name: Notification.Name("XS_VideoProgress"), object: 0)
            player.playerView.isHidden = true
            
            if item.source == "cloudLearn" {
//                var vidStr = item.vid
//                if item.vid.contains("?") {
//                    vidStr = ""
//                    let vidArr = item.vid.components(separatedBy: "?")
//                    for (index, itemStr) in vidArr.enumerated() {
//                        if index == 0 {
//                            vidStr.append(itemStr)
//                            vidStr.append("?")
//                        } else {
//                            var tempStr = itemStr
//                            tempStr = tempStr.replacingOccurrences(of: "/", with: "%2F")
//                            tempStr = tempStr.replacingOccurrences(of: "+", with: "%2B")
//                            if index == vidArr.count - 1 {
//                                vidStr.append(tempStr)
//                            } else {
//                                vidStr.append(tempStr)
//                                vidStr.append("?")
//                            }
//                        }
//                    }
//                }
//                let urlSource = AVPUrlSource()
//                urlSource.playerUrl = URL(string: vidStr)
//                player.setUrlSource(urlSource)
                
                let liveStsSource = AVPLiveStsSource()
                liveStsSource.url = item.vid
//                liveStsSource.region = item.regionId
//                liveStsSource.securityToken = item.stk
//                liveStsSource.accessKeySecret = item.akScret
//                liveStsSource.accessKeyId = item.akId
                player.setLiveStsSource(liveStsSource)
            } else {
                //创建VidSts
                let source = AVPVidStsSource()
                source.region = item.regionId
                source.vid = item.vid
                source.securityToken = item.stk
                source.accessKeySecret = item.akScret
                source.accessKeyId = item.akId
                //设置播放源
                player.setStsSource(source)
            }
            //准备播放
            player.prepare()
            self.startBtn.alpha = 1
            self.botView.isHidden = true
        }).disposed(by: disposeBag)
        
        livePS.subscribe(onNext: { [weak self] urlStr in
            self?.playBtn.alpha = 0
            self?.timeLab.alpha = 0
            self?.slider.alpha = 0
            let source = AVPUrlSource()
            source.playerUrl = URL(string: urlStr)
            //设置播放源
            player.setUrlSource(source)
            //准备播放
            player.prepare()
        }).disposed(by: disposeBag)
        
//        //创建VidSts
//            AVPVidStsSource *source = [[AVPVidStsSource alloc] init];
//            source.region = self.接入区域;
//            source.vid = self.视频vid;
//            source.securityToken = self.安全token;
//            source.accessKeySecret = self.临时akSecret;
//            source.accessKeyId = self.临时akId;
//             //设置播放源
//            [self.player setStsSource:source];
//             //准备播放
//            [self.player prepare];
    }
    func getImg(_ color: UIColor) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: 12, height: 12)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.addArc(center: CGPoint(x: 6, y: 6), radius: 6, startAngle: 0, endAngle: .pi*2, clockwise: true)
        context?.setFillColor(color.cgColor)
        context?.fillPath()
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img
    }
}

extension XS_KCVideo {
    func toFull() {
        guard !isFullScreen, let window = xsWindow() else { return }
        
        fullBtn.isSelected = true
        self.isFullScreen = true
        self.oldFrame = playerView.frame
        self.windowFrame = playerView.convert(playerView.bounds, to: window)
        
        playerView.removeFromSuperview()
        playerView.frame = self.windowFrame
        window.addSubview(playerView)

        self.fullVC.shouldClose = true
        UIView.animate(withDuration: 0.25, animations: {
            self.topView.alpha = 1
            self.playerView.frame = CGRect(x: 0, y: 0, width: .screenHeight, height: .screenWidth)
            XS_NVC.shared.present(self.fullVC, animated: true)
            self.playerView.layoutSubviews()
        }) { _ in
            window.bringSubviewToFront(self.playerView)
        }
    }
    func backFull() {
        guard isFullScreen else { return }
        
        fullBtn.isSelected = false
        isFullScreen = false
        UIView.animate(withDuration: 0.25, animations: {
            self.topView.alpha = 0
            self.playerView.frame = self.windowFrame
            self.fullVC.dismiss(animated: true)
            self.playerView.layoutSubviews()
        }) { _ in
            self.playerView.removeFromSuperview()
            self.playerView.frame = self.oldFrame
            self.addSubview(self.playerView)
            self.playerView.layoutSubviews()
        }
    }
}

extension XS_KCVideo: AVPDelegate {
    func onPlayerStatusChanged(_ player: AliPlayer!, oldStatus: AVPStatus, newStatus: AVPStatus) {
        switch newStatus {
        case .init(4), .init(5), .init(6): // 播放完成
            playBtn.isSelected = false
        case .init(3): // 正在播放
            playBtn.isSelected = true
            player.playerView.isHidden = false
        case .init(2): // 准备完成
            startBtn.isHidden = false
        default: break
        }
    }
    
    func onCurrentPositionUpdate(_ player: AliPlayer!, position: Int64) {
        timeLab.text = "\(position.toTimeStr())/\(player.duration.toTimeStr())"
        let progress = CGFloat(position)/CGFloat(player.duration)
        slider.value = Float(progress)
        NotificationCenter.default.post(name: Notification.Name("XS_VideoProgress"), object: progress)
    }
    
    func onError(_ player: AliPlayer!, errorModel: AVPErrorModel!) {
//        print("----->>>>>\(errorModel.code)->\(String(describing: errorModel.message))->\(String(describing: errorModel.requestId))->\(String(describing: errorModel.videoId))")
    }
}
